//
//  TMInvitationController.m
//  国学商家管理
//
//  Created by Tao Li on 2018/6/21.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "TMInvitationController.h"
#import "TMCheckActionView.h"
#import "TMTQGCodeCell.h"
#import "TMInviteAwardCell.h"
#import "TMFinanicalCell.h"
#import "TMShareView.h"
#import "TMWithdrawController.h"
#import "TMShareManager.h"
#import "TMInComeCell.h"
#import "TMUserViewModel.h"
#import "TMInvitationMoneyModel.h"
@interface TMInvitationController ()<UITextFieldDelegate,UITextViewDelegate>
@property (nonatomic, assign) BOOL isqgcode;
@property (nonatomic, strong) TMUserViewModel *viewModel;
@property (nonatomic, copy) NSString *invacationCode;
@property (nonatomic, strong) TMInvitationMoneyModel *invitationModel;
@property (nonatomic, assign) NSInteger checkIndex;
@property (nonatomic, copy) NSString *invacationNum;
@end

@implementation TMInvitationController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //[self.tableView.mj_header beginRefreshing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的邀请";
    [self displayAllCells];
    [self registerForKeyboardNotifications];
    self.isqgcode = YES;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.viewModel = [[TMUserViewModel alloc]init];
    //        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    [self getData];
    //}];
    // [self.tableView.mj_header beginRefreshing];
    self.tableView.tableFooterView = [UIView new];
    
}
- (void)displayAllCells{
    [self.tableView registerNib:[UINib nibWithNibName:@"TMTQGCodeCell" bundle:nil] forCellReuseIdentifier:@"TMTQGCodeCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TMInviteAwardCell" bundle:nil] forCellReuseIdentifier:@"TMInviteAwardCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TMFinanicalCell" bundle:nil] forCellReuseIdentifier:@"TMFinanicalCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TMInComeCell" bundle:nil] forCellReuseIdentifier:@"TMInComeCell"];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isqgcode == YES) {
        return 1;
    }else{
        if (self.invitationModel){
            if (self.invitationModel.data.count> 0 && self.invitationModel.detail.count>0) {
                return 4;
            }else{
                if ((self.invitationModel.data.count == 0 && self.invitationModel.detail.count>0) || (self.invitationModel.data.count > 0 && self.invitationModel.detail.count == 0)) {
                    return 3;
                }else{
                    return 2;
                }
            }
        }else{
            return 0;
            
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isqgcode == YES) {
        TMTQGCodeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMTQGCodeCell" forIndexPath:indexPath];
        //cell.codeImage.image = [self createNonInterpolatedUIImageFormString:@"iostest" withSize:92.0f];
//        cell.codeImage.hidden = YES;
        [cell.codeImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithBaseUrl:self.invacationCode]] placeholderImage:kPlaceholder];
        __weak typeof(cell) weakself = cell;
        cell.blocks = ^{
            NSString *shareTitle;
            NSString *shareDis;
            if (!weakself.titleTF.text || weakself.titleTF.text.length <= 0) {
                shareTitle = @"快乐教育，尽在云学π教育平台";
            }else{
                shareTitle = weakself.titleTF.text;
            }
            if (!weakself.textView.text || weakself.textView.text.length <= 0) {
                shareDis = @"选择云学π平台，分享教育心得";
            }else{
                shareDis = weakself.textView.text;
            }
            NSString *shareContent = [NSString stringWithFormat:@"我的邀请码[%@],%@", self.invacationNum,shareDis];
            TMShareView *views = [[NSBundle mainBundle] loadNibNamed:@"TMShareView" owner:nil options:nil].lastObject;
            views.frame = self.navigationController.view.bounds;
            [self.navigationController.view addSubview:views];
            //share
            __weak typeof(views) weakview = views;
            views.qqBlock = ^{
                [[TMShareManager defaultManager]shareToQQWithParam:@{
                                                                     @"image":weakself.codeImage.image,@"discript":shareContent,@"title":shareTitle
                                                                     } Success:^(id respone){
                                                                         [self.tableView.mj_header beginRefreshing];
                                                                         weakself.titleTF.text = nil;
                                                                         weakself.textView.text = nil;
                                                                         weakself.placeLabel.hidden = NO;
                                                                         [weakview removeFromSuperview];
                                                                     }];
            };
            views.wbBlock = ^{
                [[TMShareManager defaultManager] shareToWBWithParam:@{} Success:^(id resopne){
                    
                }];
            };
            views.wxBlock = ^{
                [[TMShareManager defaultManager] shareToWXWithParam:@{
                                                                      @"image":weakself.codeImage.image,@"discript":shareContent,@"title":shareTitle
                                                                      } Success:^(id respone){
                                                                          [self.tableView.mj_header beginRefreshing];
                                                                          weakself.titleTF.text = nil;
                                                                          weakself.textView.text = nil;
                                                                          weakself.placeLabel.hidden = NO;
                                                                          [weakview removeFromSuperview];
                                                                      }];
            };
            //朋友圈
            views.wxcBlock = ^{
                [[TMShareManager defaultManager] shareToWXCWithParam:@{
                                                                       @"image":weakself.codeImage.image,@"discript":shareContent,@"title":shareTitle
                                                                       } Success:^(id respone){
                                                                           [self.tableView.mj_header beginRefreshing];
                                                                           weakself.titleTF.text = nil;
                                                                           weakself.textView.text = nil;
                                                                           weakself.placeLabel.hidden = NO;
                                                                           [weakview removeFromSuperview];
                                                                       }];
            };
        };
        return cell;
    }else{
        if (indexPath.row == 0) {
            TMInviteAwardCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMInviteAwardCell" forIndexPath:indexPath];
            cell.backgroundColor = [UIColor hx_colorWithHexRGBAString:@"FAFAFA"];
            cell.model = self.invitationModel;
            return cell;
        }if (indexPath.row == 1) {
            TMFinanicalCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMFinanicalCell" forIndexPath:indexPath];
            cell.backgroundColor = [UIColor hx_colorWithHexRGBAString:@"FAFAFA"];
            cell.getMoneyOutButton.hidden = NO;
            [cell.getMoneyOutButton setTitle:@"提现" forState:UIControlStateNormal];
            cell.saleMoneyLabel.hidden = YES;
            cell.saleImage.hidden = YES;
            cell.block = ^{
                //提现
                TMWithdrawController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"TMWithdrawController"];
                vc.outMoney = [self.invitationModel.yao floatValue];
                [self.navigationController pushViewController:vc animated:YES];
            };
            return cell;
        }
        if (indexPath.row == 2) {
            TMInComeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMInComeCell" forIndexPath:indexPath];
            if (self.invitationModel.data.count) {
                [cell.detailTitleType setTitle:@"邀请明细" forState:UIControlStateNormal];
                cell.isFanical = YES;
                cell.listArray = self.invitationModel.data.mutableCopy;
                [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isuse"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }else{
                [cell.detailTitleType setTitle:@"消费明细" forState:UIControlStateNormal];
                cell.isFanical = YES;
                cell.listArray = self.invitationModel.detail.mutableCopy;
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isuse"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            return cell;
        }
        if (indexPath.row == 3) {
            TMInComeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMInComeCell" forIndexPath:indexPath];
            [cell.detailTitleType setTitle:@"消费明细" forState:UIControlStateNormal];
            cell.isFanical = YES;
            cell.listArray = self.invitationModel.detail.mutableCopy;
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isuse"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            return cell;
        }
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isqgcode == YES) {
        return 490*kWindowW/375;
    }else{
        if (indexPath.row == 0) {
            return 155;
        }
        if (indexPath.row == 1) {
            return  84*kWindowW/375;
        }if (indexPath.row == 2 || indexPath.row == 3) {
            return 40*5+ 77;
        }
    }
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    TMCheckActionView *vc =  [[NSBundle mainBundle] loadNibNamed:@"TMCheckActionView" owner:self options:nil].lastObject;
    [vc.fristBTN setTitle:@"邀请码" forState:UIControlStateNormal];
    [vc.secondBtn setTitle:@"邀请奖励" forState:UIControlStateNormal];
    //__weak typeof(vc) weakself = vc;
    vc.block = ^(NSInteger index) {
        //        weakself.isCheck = index + 1;
        [[NSUserDefaults standardUserDefaults] setInteger:index+1 forKey:@"indexss"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if (index == 0) {
            self.isqgcode = YES;
            [self getData];
        }else{
            self.isqgcode = NO;
            [self getData];
        }
        // [self.tableView.mj_header beginRefreshing];
    };
    return vc;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
   // return  74*kWindowW/375;
    return 0;
}

- (UIImage *)createNonInterpolatedUIImageFormString:(NSString *)str withSize:(CGFloat) size
{
    //1. 实例化二维码滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2. 恢复滤镜的默认属性
    [filter setDefaults];
    // 3. 将字符串转换成NSData
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    // 4. 通过KVO设置滤镜inputMessage数据
    [filter setValue:data forKey:@"inputMessage"];
    // 5. 获得滤镜输出的图像
    CIImage *outputImage = [filter outputImage];
    CGRect extent = CGRectIntegral(outputImage.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:outputImage fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"indexss"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return false;
    }
    return true;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if ([textField isFirstResponder]) {
        [textField resignFirstResponder];
    }
    return YES;
}
- (void) registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void) keyboardWillShow:(NSNotification *) notif
{
    //获取键盘的高度
    NSDictionary *userInfo = [notif userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    CGFloat duration = [notif.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
    [UIView animateWithDuration:duration animations:^{
        self.tableView.frame = CGRectMake(0, -216, kWindowW, kWindowH);
    } completion:^(BOOL finished) {
        
    }];
    
}
- (void) keyboardWillHide:(NSNotification *) notif
{
    
    // self.commentViewBG.buttomConstrain.constant = -150;
    CGFloat duration = [notif.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
    [UIView animateWithDuration:duration animations:^{
        self.tableView.frame = CGRectMake(0, 0, kWindowW, kWindowH);
    } completion:^(BOOL finished) {
        [self.view layoutIfNeeded];
    }];
    
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)getData{
    if (self.isqgcode == YES) {
        [self.viewModel getInvacationCodeWithSuccess:^(id responseObject) {
            self.invacationCode = responseObject[@"ios"];
            //[self.tableView.mj_header endRefreshing];
            self.invacationNum = responseObject[@"view"];
            [self.tableView reloadData];
        } AndFiled:^(NSString *error) {
            //[self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
        }];
    }else{
        
        [self.viewModel getInvacationMoneyWithSuccess:^(id responseObject) {
            self.invitationModel = responseObject;
            //[self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
        } AndFiled:^(NSString *error) {
            //[self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
        }];
    }
}

@end
